﻿using System;
using DBProvider;
using DBProvider.Providers;

namespace HealthCommunity
{
	public partial class Register1 : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			var qq = txtQQID.Text.Trim();
			var qqidProvider = new QQIDProvider();

			var isexist = qqidProvider.IsExist(qq);

			if(!isexist)
			{
				var qqid = new QQID()
				{
					QQID1 = qq,
					SubmitTime = DateTime.Now,
					ActivationState = (int)QQActivationState.NotActivated,
					ActivationCode = Guid.NewGuid().ToString()
				};

				try
				{
					var msg = string.Empty;
					var theNewQQID = qqidProvider.CreateQQID(qqid, out msg);
					if(theNewQQID != null)
					{
						var activeURL = string.Format("http://{0}/Activation.aspx?qqid={1}&activationcode={2}", Request.Url.Host, theNewQQID.QQID1, theNewQQID.ActivationCode);
						var subject = "邮箱激活";
						var body = @"点击以下链接激活您的帐户: " + activeURL;
						var to = theNewQQID.QQID1 + "@qq.com";

						CommonHelper.SendMail(to, subject, body);
						ltrMsg.Text = "请检查您的qq邮箱,激活链接已发送到您的邮箱,24小时之内激活有效.";
					}
					else
					{
						ltrMsg.Text = msg;
					}
				}
				catch(System.Net.Mail.SmtpException smtpexc)
				{
					ltrMsg.Text = smtpexc.Message;
				}
				catch(Exception exc)
				{
					ltrMsg.Text = exc.Message;
				}
			}
			else
			{
				var qqid = qqidProvider.GetQQID(qq);

				if(qqid.ActivationState == (int)QQActivationState.Activated)
				{
					ltrMsg.Text = "该qq号已注册,不能再次注册";
				}
				else
				{
					qqid.ActivationCode = Guid.NewGuid().ToString();
					qqid.SubmitTime = DateTime.Now;
					qqid.ActivationState = (int)QQActivationState.NotActivated;

					try
					{
						var msg = string.Empty;
						if(qqidProvider.UpdateQQID(qqid))
						{
							var activeURL = string.Format("http://{0}/Activation.aspx?qqid={1}&activationcode={2}", Request.Url.Host, qqid.QQID1, qqid.ActivationCode);
							var subject = "邮箱激活";
							var body = @"点击以下链接激活您的帐户: " + activeURL;
							var to = qqid.QQID1 + "@qq.com";

							CommonHelper.SendMail(to, subject, body);
							ltrMsg.Text = "请检查您的qq邮箱,激活链接已发送到您的邮箱,24小时之内激活有效.";
						}
						else
						{
							ltrMsg.Text = msg;
						}
					}
					catch(System.Net.Mail.SmtpException smtpexc)
					{
						ltrMsg.Text = smtpexc.Message;
					}
					catch(Exception exc)
					{
						ltrMsg.Text = exc.Message;
					}
				}
			}
		}
	}
}